package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.BaseDocumentAddDto;
import com.kaili.basic.pojo.dto.BaseDocumentDto;
import com.kaili.basic.pojo.entity.BaseDocumentEntity;
import com.kaili.basic.pojo.vo.BaseDocumentVO;
import com.kaili.basic.service.BaseDocumentService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.fastdfs.UploadController;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.DateUtil;
import com.kaili.common.util.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Desc: 文档管理控制层
 * @author: zengshuai
 * @Time: 19-7-23 下午4:44
 * @Copyright: © 2018 杭州凯立通信有限公司 版权所有
 * @Warning: 本内容仅限于公司内部传阅, 禁止外泄或用于其它商业目的
 */
@RestController
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "文档管理", description = "文档管理相关API")
public class BaseDocumentController {

    @Autowired
    private BaseDocumentService baseDocumentService;

    @ApiOperation(value = "新增文档下发设置")
    @PostMapping("/document/down")
    public RestStatus addDocument(BaseDocumentAddDto dto,@RequestParam("file") MultipartFile file){
        BaseDocumentEntity entity = getFormData(dto,file);
        // 表示服务器下发
        entity.setPattern("1");
        // 如果结束时间不为空，表示是下发设置 ，否则表示设备主动上传
        if(entity.getEndTime() != null){
            entity.setWay("2");
        } else {
            entity.setWay("1");
        }
        baseDocumentService.addDocument(entity);
        return CommonStatus.ADD_OK;
    }

    @ApiOperation(value = "修改文档")
    @PostMapping("/document")
    public RestStatus updateDocument(HttpServletRequest request){
        BaseDocumentEntity entity = getFormData(request);
        if(baseDocumentService.selectById(entity.getId()) != null) {
            baseDocumentService.updateById(entity);
        }
        return CommonStatus.UPDATE_OK;
    }

    @ApiOperation(value = "新增文档上报设置")
    @PostMapping("/document/upload")
    public RestStatus addDocument(@RequestBody BaseDocumentAddDto dto){
        BaseDocumentEntity entity = new BaseDocumentEntity();
        BeanUtils.copyProperties(dto,entity);
        // 表示设备上传
        entity.setPattern("2");
        baseDocumentService.addDocument(entity);
        return CommonStatus.ADD_OK;
    }

    @ApiOperation(value = "修改文档上报设置")
    @PutMapping("/document/upload")
    public RestStatus updateDocument(@RequestBody BaseDocumentAddDto dto){
        BaseDocumentEntity entity = new BaseDocumentEntity();
        BeanUtils.copyProperties(dto,entity);
        if(baseDocumentService.selectById(dto.getId()) != null) {
            baseDocumentService.updateById(entity);
        }
        return CommonStatus.UPDATE_OK;
    }

    @GetMapping("/document")
    @ApiOperation(value = "分页查询文档信息")
    public Page<BaseDocumentVO> queryPageList(@ModelAttribute BaseDocumentDto dto){
        return baseDocumentService.queryPageList(new Page<BaseDocumentVO>(dto.getPage(), dto.getPageSize()), dto);
    }

    @GetMapping("/document/{id}")
    @ApiOperation(value = "根据ID查询文档信息")
    public BaseDocumentEntity queryPageList(@PathVariable("id") Integer id){
        return baseDocumentService.selectById(id);
    }

    @DeleteMapping("/document/{id}")
    @ApiOperation(value = "删除文档信息")
    public RestStatus deleteVehicleRoute(@PathVariable Long id) {
        if(baseDocumentService.selectById(id) != null){
            baseDocumentService.deleteDocument(id);
        }
        return CommonStatus.DELETE_OK;
    }

    @GetMapping(value = "/document/export")
    @ApiOperation("导出文档信息")
    public void export(HttpServletResponse response, @ModelAttribute BaseDocumentDto dto) throws Exception {
        List<BaseDocumentVO> list = baseDocumentService.queryExportList(dto);
        for (BaseDocumentVO VO: list) {
            VO.setEffectiveTime(DateUtil.getDateToStr(VO.getStartTime())+"-"+DateUtil.getDateToStr(VO.getEndTime()));
            VO.setPushAndPull(VO.getPushNumber()+"/"+VO.getPullNumber());
            VO.setSettings((VO.getAutoDelete().equals(1)?"文件自动删除/":"")+(VO.getAutoDownload().equals(1)?"移动数据网络自动下载/":"")+(!VO.getAutoDelete().equals(0)?"阅读后"+VO.getAutoDelete()+"分钟定时删除":""));
            if(VO.getSettings().equals(null)){
                VO.setSettings("");
            }
            int length = VO.getSettings().length();
            if(length != 0 &&"/".equals(VO.getSettings().substring(length-1,length))){
                VO.setSettings(VO.getSettings().substring(0,length-1));
            }
        }
        ExcelUtil.exportExcel(list,"文档信息","sheet1",BaseDocumentVO.class, UUID.randomUUID().toString()+".xls",response);
    }

    private BaseDocumentEntity getFormData(BaseDocumentAddDto dto,MultipartFile file) {
        BaseDocumentEntity entity = new BaseDocumentEntity();
        BeanUtils.copyProperties(dto,entity);
        try {
            if (file != null && file.getSize() != 0) {
                String path = UploadController.saveFile(file);
                entity.setFileUrl(path);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return entity;
    }


    private BaseDocumentEntity getFormData(HttpServletRequest request) {
        long id = Long.parseLong(request.getParameter("id"));
        String name = request.getParameter("name");
        String platform = request.getParameter("platform");
        String equipmentType = request.getParameter("equipmentType");
        String equipmentModel = request.getParameter("equipmentModel");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String remark = request.getParameter("remark");
        String pattern = request.getParameter("pattern");
        String fileUrl = request.getParameter("fileUrl");

        BaseDocumentEntity entity = new BaseDocumentEntity();
        entity.setId(id);
        entity.setName(name);
        entity.setPlatform(platform);
        entity.setEquipmentType(equipmentType);
        entity.setEquipmentModel(equipmentModel);
        entity.setPattern(pattern);
        entity.setRemark(remark);

        String fileType = request.getParameter("fileType");
        //如果文件类型不为空 说明是上报文件设置页面,否则说明是下发文件设置页面
        if (fileType != null && !fileType.trim().equals("") && !fileType.equals("null")) {
            String way = request.getParameter("way");
            String level = request.getParameter("level");
            entity.setWay(way);
            entity.setLevel(level);
            entity.setFileType(fileType);
        } else {
            double fileSize = Double.parseDouble(request.getParameter("fileSize"));
            String autoDelete = request.getParameter("autoDelete");
            String autoDownload = request.getParameter("autoDownload");
            Integer readDelete = Integer.valueOf(request.getParameter("readDelete"));
            entity.setFileSize(fileSize);
            entity.setAutoDelete(autoDelete);
            entity.setAutoDownload(autoDownload);
            entity.setReadDelete(readDelete);
        }

        try {
            entity.setStartTime(startTime);
            entity.setEndTime(endTime);
        } catch (Exception e){
            e.printStackTrace();
        }

        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
        try {
            if(file != null){
                String path = UploadController.saveFile(file);
                entity.setFileUrl(path);
            }
        } catch (IOException e){
            e.printStackTrace();
        }
        return entity;
    }

}
